<template>
  <div class="complaint-wrap">
     <!-- 顶部操作区：发布投诉 + 搜索栏 -->
    
    <div class="tool-bar">
 <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogVisible = true">
  发布投诉
      </el-button>

      <el-form :inline="true" size="small" style="margin-left: auto;">
        <el-form-item style="margin-bottom: 0;">
          <el-input
            v-model="keyword"
            placeholder="请输入姓名/房号/手机号"
            clearable
            style="width: 260px"
            @clear="fetchTable"
            @keyup.enter.native="fetchTable"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button type="primary" @click="fetchTable">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      size="small"
      style="width: 100%"
      header-cell-class-name="table-head"
    >
      <el-table-column label="小区" width="120">
        <template #default="{ row }">{{ row.communityName }}</template>
      </el-table-column>
      <el-table-column label="房间号" width="130">
        <template #default="{ row }">{{ row.roomNumber }}</template>
      </el-table-column>
      <el-table-column label="投诉日期" width="120">
        <template #default="{ row }">{{ row.complaintTime }}</template>
      </el-table-column>
      <el-table-column label="联系电话" width="130">
        <template #default="{ row }">{{ row.complaintPhone }}</template>
      </el-table-column>
      <el-table-column label="状态" width="100">
  <template #default="{ row }">
    <el-tag
      :type="row.complaintAcceptPerson ? 'success' : 'warning'"
      size="mini"
    >
      {{ row.complaintAcceptPerson ? '已受理' : '未受理' }}
    </el-tag>
  </template>
</el-table-column>
      <el-table-column label="投诉内容" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.complaintContent }}</template>
      </el-table-column>
      <el-table-column label="受理人" width="100">
        <template #default="{ row }">{{ row.complaintAcceptPerson || '--' }}</template>
      </el-table-column>
      <el-table-column label="受理时间" width="160">
        <template #default="{ row }">{{ row.complaintAcceptTime || '--' }}</template>
      </el-table-column>
      
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              v-if="!row.complaintAcceptPerson" 
              type="text"
            size="mini"
            @click="openAcceptDialog(row)"
          >受理</el-button>
          <el-button type="text" size="mini" @click="handleVisit(row)">回访</el-button>
          <el-button type="text" size="mini" @click="handleDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 受理弹窗 -->
    <el-dialog title="投诉受理" :visible.sync="acceptDialogVisible" width="400px">
      <el-form :model="acceptForm" label-width="100px">
        <el-form-item label="处理人">
          <el-input v-model="acceptForm.acceptPerson" placeholder="请输入处理人"/>
        </el-form-item>
        <el-form-item label="是否解决">
          <el-radio-group v-model="acceptForm.statusName">
            <el-radio label="已解决">已解决</el-radio>
            <el-radio label="未解决">未解决</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解决过程">
          <el-input
            type="textarea"
            v-model="acceptForm.complaintAcceptDesc"
            placeholder="请输入解决过程"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="acceptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAccept">提交</el-button>
      </div>
    </el-dialog>
    
<!-- 回访弹窗 -->
<el-dialog title="投诉回访" :visible.sync="visitDialogVisible" width="400px">
  <el-form :model="visitForm" label-width="100px">
    <el-form-item label="回访人">
      <el-input v-model="visitForm.followPerson" placeholder="请输入回访人"/>
    </el-form-item>
    <el-form-item label="是否解决">
      <el-radio-group v-model="visitForm.isSolved">
        <el-radio :label="1">已解决</el-radio>
        <el-radio :label="0">未解决</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="是否满意">
      <el-radio-group v-model="visitForm.isSatisfied">
        <el-radio :label="2">满意</el-radio>
        <el-radio :label="1">一般</el-radio>
        <el-radio :label="0">不满意</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注">
      <el-input
        type="textarea"
        v-model="visitForm.visitRemark"
        placeholder="请输入备注"
      />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="visitDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitVisit">提交</el-button>
  </div>
</el-dialog>

<!--发布投诉弹窗-->
    <el-dialog title="发布投诉" :visible.sync="dialogVisible" width="400px">
      <el-form :model="complaintForm" label-width="100px">
        <!-- 投诉人 -->
        <el-form-item label="投诉人">
          <el-input v-model="complaintForm.complaintPerson" placeholder="请输入投诉人"></el-input>
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话">
          <el-input v-model="complaintForm.complaintPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <!-- 投诉时间 -->
        <el-form-item label="投诉时间">
          <el-date-picker
            v-model="complaintForm.complaintTime"
            type="date"
            placeholder="请选择投诉时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <!-- 投诉内容 -->
        <el-form-item label="投诉内容">
          <el-input type="textarea" v-model="complaintForm.complaintContent" placeholder="请输入投诉内容"></el-input>
        </el-form-item>

        <!-- 小区选择 -->
        <el-form-item label="小区">
          <el-select v-model="complaintForm.communityId" placeholder="请选择小区" @change="handleCommunityChange">
            <el-option
                v-for="c in communityList"
                :key="c.communityId"
                :label="c.communityName"
                :value="c.communityId"
              />
          </el-select>
        </el-form-item>

        <!-- 楼栋选择 -->
        <el-form-item label="楼栋">
          <el-select v-model="complaintForm.buildingId" placeholder="请选择楼栋" @change="handleBuildingChange">
           <el-option
                v-for="b in buildingList"
                :key="b.buildingId"
                :label="b.buildingName"
                :value="b.buildingId"
              />
          </el-select>
        </el-form-item>

        <!-- 单元选择 -->
        <el-form-item label="房间号">
          <el-select v-model="complaintForm.roomId" placeholder="请选择房间号">
             <el-option
              v-for="r in roomList"
              :key="r.roomId"
              :label="r.roomNumber"
              :value="r.roomId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComplaint">提交</el-button>
      </div>
    </el-dialog>
<!--详情-->
<el-dialog :visible.sync="detailDialogVisible" title="投诉详情">
  <el-form :model="detailForm" label-width="100px">
    <el-form-item label="投诉人">{{ detailForm.complaintPerson }}</el-form-item>
    <el-form-item label="电话">{{ detailForm.complaintPhone }}</el-form-item>
    <el-form-item label="投诉时间">{{ detailForm.complaintTime }}</el-form-item>
    <el-form-item label="处理人">{{ detailForm.followPerson }}</el-form-item>
    <el-form-item label="处理时间">{{ detailForm.complaintAcceptTime }}</el-form-item>
    <el-form-item label="备注">{{ detailForm.complaintAcceptDesc }}</el-form-item>
   
  </el-form>
</el-dialog>

  </div>
</template>

<script>
import axios from 'axios'

  export default {
    name: 'ComplaintMgmt',
    data () {
      return {
        keyword: '',
        pageSize: 10,
        currentPage: 1,
        total: 0,
        tableData: [],

        // 受理弹窗
        acceptDialogVisible: false,
        acceptForm: {
          complaintId: null,
          acceptPerson: '',         // 处理人
          statusName: '未解决',     // 状态
          complaintAcceptDesc: ''   // 解决过程
        },

        // 回访弹窗
        visitDialogVisible: false,
        visitForm: {
          complaintId: null,
          followPerson: '',
          isSolved: 0,
          isSatisfied: 1,
          visitRemark: ''
        },
          dialogVisible: false,
      complaintForm: {    
        complaintPerson: '',
        complaintPhone: '',
        complaintTime: '', // 投诉时间
        complaintContent: '',
        communityId: '', // 小区ID
        buildingId: '', // 楼栋ID
        roomId: '', // 房屋ID
        complaintStatus: 0, // 状态：0未解决，1已解决
        isSatisfied: 0, // 满意度：0不满意，1一般，2满意
        complaintDesc: '', // 备注
        followPerson: '', // 回访人
        complaintAcceptDesc: '', // 受理过程
                
      },
      //详情页
      detailDialogVisible: false,
    detailForm: {
      complaintPerson: '',
      complaintPhone: '',
      complaintTime: '',
      followPerson: '',
      complaintAcceptTime: '',
      complaintAcceptDesc: '',
      communityName: '',
      buildingName: '',
      buildingUnit: '',
      roomNumber: '',
      fullAddress: ''
    },
       communityList: [],
       buildingList: [],
        roomList: [],
      
      



      }
    },
    created () {
       this.fetchCommunities();
      this.fetchTable()
    },
    methods: {
      // 获取表格数据/
      fetchTable() {
  const payload = {
    page: this.currentPage,
    size: this.pageSize,
    keyword: this.keyword
  };

  let url = this.keyword
    ? "http://localhost:8080/complaint/search"
    : "http://localhost:8080/complaint/list";

  this.$axios.post(url, payload)
    .then(res => {
      if (res.data.code === 200) {
        const pageData = res.data.data;
        this.tableData = pageData.records;
        this.total = pageData.total;
      } else {
        this.$message.error(res.data.msg);
      }
    })
    .catch(err => {
      console.error(err);
      this.$message.error("接口调用失败");
    });
},

      handleCurrentChange (val) {
        this.currentPage = val
        this.fetchTable()
      },

      // 打开受理弹窗
      openAcceptDialog (row) {
        this.acceptForm.complaintId = row.complaintId
        this.acceptForm.acceptPerson = ''
        this.acceptForm.statusName = '未解决'
        this.acceptForm.complaintAcceptDesc = ''
        this.acceptDialogVisible = true
      },

      // 提交受理
      async submitAccept () {
        try {
          const res = await axios.post('http://localhost:8080/complaint/accept', this.acceptForm)
          if (res.data.code === 200) {
            this.$message.success('受理成功')
            this.acceptDialogVisible = false
            this.fetchTable()
          } else {
            this.$message.error(res.data.message || '受理失败')
          }
        } catch (e) {
          console.error(e)
          this.$message.error('接口调用失败')
        }
      },

      // 打开回访弹窗
      handleVisit (row) {
        this.visitForm = {
         complaintId: row.complaintId,
            followPerson: this.visitForm.followPerson,
            isSolvedName: this.visitForm.isSolved === 1 ? "已解决" : "未解决",
            isSatisfiedName: this.visitForm.isSatisfied === 2 ? "满意" :
                            this.visitForm.isSatisfied === 1 ? "一般" : "不满意",
            visitRemark: this.visitForm.visitRemark
        }
        this.visitDialogVisible = true
        console.log('回访投诉ID:', row.complaintId);
      },
  // 提交回访
  async submitVisit() {
    try {
      
      const res = await axios.post(
        'http://localhost:8080/complaint/followUp', 
        this.visitForm, 
        {
          headers: { 'Content-Type': 'application/json' } 
        }
      );

      if (res.data.code === 200) {
        this.$message.success('回访成功');
        this.visitDialogVisible = false;
        this.fetchTable(); // 刷新表格
      } else {
        this.$message.error(res.data.msg || '回访失败');
      }
    } catch (err) {
      console.error('接口调用失败:', err);
      this.$message.error('接口调用失败');
    }
  },
      // 查看详情
      handleDetail(row) {
  // row.complaintId 是你要查询的投诉ID
  this.$axios.get(`http://localhost:8080/complaint/${row.complaintId}`)
    .then(res => {
      if (res.data.code === 200) {
        const detail = res.data.data;

        // 弹窗显示或赋值表单
        this.detailDialogVisible = true;
        this.detailForm = {
          complaintPerson: detail.complaintPerson,
          complaintPhone: detail.complaintPhone,
          complaintTime: detail.complaintTime,
          followPerson: detail.followPerson,
          complaintAcceptTime: detail.complaintAcceptTime,
          complaintAcceptDesc: detail.complaintAcceptDesc,
          communityName: detail.communityName,
          buildingName: detail.buildingName,
          buildingUnit: detail.buildingUnit,
          roomNumber: detail.roomNumber,
          fullAddress: detail.fullAddress
        };
      } else {
        this.$message.error(res.data.msg);
      }
    })
    .catch(err => {
      console.error(err);
      this.$message.error('获取投诉详情失败');
    });
},
        // 提交投诉
    submitComplaint() {
         const mockComplaint = {
    complaintPerson: '张三',
    complaintPhone: '123456789',
    complaintTime: this.formatDate(new Date()), // 使用当前时间
    complaintContent: '水管漏水',
    communityId: '1968125183214604288', // 假定选择的小区ID
    buildingId: 'B001', // 假定选择的楼栋ID
    roomId: 'R001', // 假定选择的房间ID
    complaintStatus: 0, // 0: 未解决
    isSatisfied: 0, // 0: 不满意
    complaintDesc: '漏水情况较为严重',
    followPerson: '李四',
    complaintAcceptDesc: '已报修'
  };

    
      this.complaintForm.complaintTime = this.formatDate(this.complaintForm.complaintTime); // 格式化投诉时间

      // 调用后端接口提交投诉数据
      axios.post('http://localhost:8080/complaint/add', mockComplaint)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('投诉发布成功');
            this.dialogVisible = false;
            this.resetForm(); // 清空表单
          } else {
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.error(error);
          this.$message.error('发布投诉失败');
        });
    },

    // 格式化日期为yyyy-MM-dd
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 清空表单
    resetForm() {
      this.complaintForm = {
        complaintId: '',
        complaintPerson: '',
        complaintPhone: '',
        complaintTime: '',
        complaintContent: '',
        communityId: '',
        buildingId: '',
        roomId: '',
        complaintStatus: 0,
        isSatisfied: 0,
        complaintDesc: '',
        followPerson: '',
        complaintAcceptDesc: ''
        
      };
    },
    //查小区
  fetchCommunities() {
    this.$axios.get('http://localhost:8080/community/selcomm').then(res => {
    if (res.data.code === 200) {
      this.communityList = res.data.data;
      
    } else {
      this.$message.error(res.data.message);
    }
  });
  },
 handleCommunityChange(communityId) {
    this.selectedCommunityId = communityId;
    this.fetchBuildings(communityId);
    this.roomList = []; // 清空房号
  },
  //查楼栋
  fetchBuildings(communityId) {
   this.$axios.get(`/building/list?communityId=${communityId}`).then(res => {
    if (res.data.code === 200) {
      this.buildingList = res.data.data;
    }
  });
  },
  handleBuildingChange(buildingId) {
    this.selectedBuildingId = buildingId;
    this.fetchRooms(buildingId);
  },
  //查房号
 fetchRooms(buildingId) {
     this.$axios.get(`http://localhost:8080/room/list?buildingId=${buildingId}`).then(res => {
    if (res.data.code === 200) {
      this.roomList = res.data.data;
    }
  });
  }



    },
    watch: {
  dialogVisible(newVal) {
    if (newVal) {
      // 弹窗打开时填充默认数据
      this.complaintForm = {
        complaintPerson: '张三',
        complaintPhone: '123456789',
        complaintTime: this.formatDate(new Date()),
        complaintContent: '水管漏水',
        communityId: '1968125183214604288', // 假设小区ID
        buildingId: 'B001', // 假设楼栋ID
        roomId: 'R001',      // 假设房间ID
        complaintStatus: 0,
        isSatisfied: 0,
        complaintDesc: '漏水情况较为严重',
        followPerson: '李四',
        complaintAcceptDesc: '已报修'
      };
    }
  }
}
  }
  </script>


<style scoped>
.complaint-wrap {
  padding: 20px;
  background: #fff;
}
.page-title {
  margin: 0 0 15px 0;
  font-size: 18px;
}
.tool-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
.table-head {
  background: #f5f7fa !important;
}
</style>



<style scoped>
.complaint-wrap {
  padding: 20px;
  background: #fff;
}
.page-title {
  margin: 0 0 15px 0;
  font-size: 18px;
}
.tool-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
.table-head {
  background: #f5f7fa !important;
}
</style>